import UIKit
import MarkdownUIKit
import Down
import SnapKit

class MarkdownDetailViewController: UIViewController {
    // MARK: - Properties
    private var markdownView: MarkdownContentView?
    private var editorView: UITextView = {
        let textView = UITextView()
        textView.font = .systemFont(ofSize: 16)
        textView.autocapitalizationType = .none
        textView.autocorrectionType = .no
        textView.isHidden = true
        return textView
    }()
    
    private var isDarkMode = false
    private var isPreviewMode = true
    private var keyboardHeight: CGFloat = 0
    private lazy var panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
    private let markdownContent: String
    
    // MARK: - Initialization
    init(title: String, markdownContent: String) {
        self.markdownContent = markdownContent
        super.init(nibName: nil, bundle: nil)
        self.title = title
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupNavigationBar()
        setupMarkdownView()
        setupEditorView()
        loadMarkdown()
    }
    
    // MARK: - Setup
    private func setupUI() {
        view.backgroundColor = .systemBackground
        
        let markdownView = MarkdownContentView()
        markdownView.delegate = self
        view.addSubview(markdownView)
        view.addSubview(editorView)
        
        // 添加手势识别
        editorView.addGestureRecognizer(panGesture)
        panGesture.delegate = self
        
        // 更新约束，考虑键盘高度
        markdownView.snp.makeConstraints { make in
            make.top.left.right.equalTo(view.safeAreaLayoutGuide)
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-keyboardHeight)
        }
        
        editorView.snp.makeConstraints { make in
            make.top.left.right.equalTo(view.safeAreaLayoutGuide)
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-keyboardHeight)
        }
        
        self.markdownView = markdownView
        
        // 注册键盘通知
        registerKeyboardNotifications()
    }
    
    private func setupNavigationBar() {
        // 创建主题切换按钮
        let themeButton = UIButton(type: .system)
        themeButton.addTarget(self, action: #selector(themeButtonTapped), for: .touchUpInside)
        if #available(iOS 13.0, *) {
            themeButton.setImage(UIImage(systemName: isDarkMode ? "sun.max.fill" : "moon.fill"), for: .normal)
        } else {
            themeButton.setTitle(isDarkMode ? "浅色" : "深色", for: .normal)
        }
        
        // 创建预览切换按钮
        let previewButton = UIButton(type: .system)
        previewButton.addTarget(self, action: #selector(previewButtonTapped), for: .touchUpInside)
        if #available(iOS 13.0, *) {
            previewButton.setImage(UIImage(systemName: isPreviewMode ? "chevron.left.forwardslash.chevron.right" : "eye.fill"), for: .normal)
        } else {
            previewButton.setTitle(isPreviewMode ? "编辑" : "预览", for: .normal)
        }
        
        // 创建按钮容器视图
        let buttonStackView = UIStackView(arrangedSubviews: [themeButton, previewButton])
        buttonStackView.spacing = 16
        buttonStackView.distribution = .fillEqually
        
        // 设置导航栏右侧按钮
        navigationItem.rightBarButtonItems = [
            UIBarButtonItem(customView: buttonStackView)
        ]
        
        // 添加返回按钮
        let backButton = UIButton(type: .system)
        backButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
        backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
    }
    
    private func setupMarkdownView() {
        let config = MarkdownConfiguration()
        
        // 配置代码块选项
        config.codeBlockOptions.showHeader = true
        config.codeBlockOptions.showLanguageLabel = true
        config.codeBlockOptions.showCopyButton = true
        config.codeBlockOptions.languageLabelFont = .systemFont(ofSize: 12, weight: .medium)
        config.codeBlockOptions.copyButtonImage = UIImage(systemName: "doc.on.doc")
        config.codeBlockOptions.headerBackgroundColor = .systemGray6
        config.codeBlockOptions.languageLabelTextColor = .secondaryLabel
        config.codeBlockOptions.copyButtonTintColor = .secondaryLabel
        config.codeBlockOptions.onCopy = { [weak self] in
            self?.showCopyFeedback()
        }
        
        let markdownView = MarkdownContentView(configuration: config)
        markdownView.delegate = self
        markdownView.theme = .light
        markdownView.updateCodeBlockStyle(.light)
        view.addSubview(markdownView)
        markdownView.snp.makeConstraints { make in
            make.edges.equalTo(view.safeAreaLayoutGuide)
        }
        
        self.markdownView = markdownView
        
        // 注册自定义视图
        registerCustomViews()
    }
    
    private func showCopyFeedback() {
        let feedbackGenerator = UIImpactFeedbackGenerator(style: .medium)
        feedbackGenerator.prepare()
        feedbackGenerator.impactOccurred()
        
        // 可以添加一个临时的提示视图
        let feedbackLabel = UILabel()
        feedbackLabel.text = "已复制"
        feedbackLabel.textColor = .white
        feedbackLabel.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        feedbackLabel.textAlignment = .center
        feedbackLabel.layer.cornerRadius = 15
        feedbackLabel.layer.masksToBounds = true
        feedbackLabel.alpha = 0
        
        view.addSubview(feedbackLabel)
        feedbackLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(80)
            make.height.equalTo(30)
        }
        
        UIView.animate(withDuration: 0.3, animations: {
            feedbackLabel.alpha = 1
        }) { _ in
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                UIView.animate(withDuration: 0.3, animations: {
                    feedbackLabel.alpha = 0
                }) { _ in
                    feedbackLabel.removeFromSuperview()
                }
            }
        }
    }
    
    private func setupEditorView() {
        editorView.delegate = self
        editorView.text = markdownContent
        
        // 添加工具栏
        let toolbar = UIToolbar()
        toolbar.sizeToFit()
        
        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissKeyboard))
        
        toolbar.items = [flexSpace, doneButton]
        editorView.inputAccessoryView = toolbar
    }
    
    private func registerCustomViews() {
        // 注册引用标签视图
        markdownView?.registerCustomHTMLNodeView(forTag: "a", className: "ncTag") { [weak self] attributes, content in
            let label = PaddingLabel()
            label.numberOfLines = 0
            label.text = content
            
            // 设置样式
            let blueColor = { () -> UIColor in
                if #available(iOS 13.0, *) {
                    return UIColor { traitCollection in
                        return traitCollection.userInterfaceStyle == .dark ? 
                            UIColor(red: 10/255, green: 132/255, blue: 1, alpha: 1) :
                            UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
                    }
                } else {
                    return UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
                }
            }()
            
            label.backgroundColor = blueColor.withAlphaComponent(0.1)
            label.textColor = blueColor
            label.font = .systemFont(ofSize: 16)
            label.layer.cornerRadius = 4
            label.layer.masksToBounds = true
            label.padding = UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4)
            label.textAlignment = .center
            
            // 启用用户交互
            label.isUserInteractionEnabled = true
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self?.handleReference(_:)))
            label.addGestureRecognizer(tapGesture)
            
            // 存储内容
            if let gestureLabel = tapGesture.view as? UILabel {
                gestureLabel.text = "1"
            }
            label.bounds = CGRect(origin: .zero, size: CGSize(width: 20, height: 20))
            label.layer.cornerRadius = 10
            label.clipsToBounds = true
            return label
        }
        
        // 注册用户标签视图
        markdownView?.registerCustomHTMLNodeView(forTag: "a", className: "userTag") { [weak self] attributes, content in
            let label = PaddingLabel()
            label.numberOfLines = 0
            label.text = content
            
            // 设置样式
            let greenColor: UIColor = .systemGreen
            
            label.backgroundColor = greenColor.withAlphaComponent(0.1)
            label.textColor = greenColor
            label.font = .systemFont(ofSize: 16)
            label.textAlignment = .center
            //label.bounds = CGRect(origin: .zero, size: CGSize(width: 20, height: 20))
            label.layer.cornerRadius = 10
            label.clipsToBounds = true
            label.padding = UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4)
            label.sizeToFit()
            label.bounds = CGRect(origin: .zero, size: CGSize(width: max(20, label.bounds.size.width), height: 20))
            
            return label
        }
        
        markdownView?.registerCustomHTMLNodeView(forTag: "span", className: "ncTag") { [weak self] attributes, content in
            let label = PaddingLabel()
            label.numberOfLines = 0
            label.text = content
            
            // 设置样式
            let greenColor: UIColor = .systemPink
            
            label.backgroundColor = greenColor.withAlphaComponent(0.1)
            label.textColor = greenColor
            label.font = .systemFont(ofSize: 16)
            label.textAlignment = .center
            //label.bounds = CGRect(origin: .zero, size: CGSize(width: 20, height: 20))
            label.layer.cornerRadius = 10
            label.clipsToBounds = true
            label.padding = UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4)
            label.sizeToFit()
            label.bounds = CGRect(origin: .zero, size: CGSize(width: max(20, label.bounds.size.width), height: 20))
           
            return label
        }
    }
    
    private func loadMarkdown() {
        // 设置初始主题
        markdownView?.theme = .light
        
        // 设置初始代码块样式
        markdownView?.updateCodeBlockStyle(.light)
        
        // 设置图片基础 URL（如果需要）
        if let baseURL = Bundle.main.url(forResource: "Images", withExtension: nil) {
            markdownView?.imageBaseURL = baseURL
        }
        
        // 加载初始 Markdown 内容
        markdownView?.render(markdownContent)
    }
    
    // MARK: - Custom Tag Handlers
    @objc private func handleReference(_ gesture: UITapGestureRecognizer) {
        guard let label = gesture.view as? UILabel,
              let content = label.text else {
            return
        }
        
        // 处理引用点击
        print("Reference tapped: \(content)")
        // 这里可以添加引用跳转逻辑
    }
    
    @objc private func handleUserTag(_ gesture: UITapGestureRecognizer) {
        guard let label = gesture.view as? UILabel,
              let content = label.text else {
            return
        }
        
        // 处理用户标签点击
        print("User tag tapped: \(content)")
        // 这里可以添加用户页面跳转逻辑
    }
    
    // MARK: - Actions
    @objc private func themeButtonTapped() {
        isDarkMode.toggle()
        updateTheme()
        
        // 更新按钮图标
        if #available(iOS 13.0, *) {
            if let themeButton = (navigationItem.rightBarButtonItems?.first?.customView as? UIStackView)?.arrangedSubviews.first as? UIButton {
                themeButton.setImage(UIImage(systemName: isDarkMode ? "sun.max.fill" : "moon.fill"), for: .normal)
            }
        } else {
            if let themeButton = (navigationItem.rightBarButtonItems?.first?.customView as? UIStackView)?.arrangedSubviews.first as? UIButton {
                themeButton.setTitle(isDarkMode ? "浅色" : "深色", for: .normal)
            }
        }
    }
    
    @objc private func previewButtonTapped() {
        isPreviewMode.toggle()
        editorView.isHidden = isPreviewMode
        markdownView?.isHidden = !isPreviewMode
        
        // 更新按钮图标
        if #available(iOS 13.0, *) {
            if let previewButton = (navigationItem.rightBarButtonItems?.first?.customView as? UIStackView)?.arrangedSubviews.last as? UIButton {
                previewButton.setImage(UIImage(systemName: isPreviewMode ? "chevron.left.forwardslash.chevron.right" : "eye.fill"), for: .normal)
            }
        } else {
            if let previewButton = (navigationItem.rightBarButtonItems?.first?.customView as? UIStackView)?.arrangedSubviews.last as? UIButton {
                previewButton.setTitle(isPreviewMode ? "编辑" : "预览", for: .normal)
            }
        }
        
        if !isPreviewMode {
            editorView.becomeFirstResponder()
        } else {
            editorView.resignFirstResponder()
            // 更新 Markdown 预览
            if let text = editorView.text {
                markdownView?.render(text)
            }
        }
    }
  
    // MARK: - Theme Handling
    private func updateTheme() {
        if #available(iOS 13.0, *) {
            if let windowScene = view.window?.windowScene {
                windowScene.windows.forEach { window in
                    window.overrideUserInterfaceStyle = isDarkMode ? .dark : .light
                }
            }
        }
        
        // 更新 Markdown 视图主题
        markdownView?.theme = isDarkMode ? .dark : .light
        
        // 保持代码块为浅色主题
        markdownView?.updateCodeBlockStyle(.light)
        
        markdownView?.reloadData()
    }
    
    // MARK: - Keyboard Handling
    private func registerKeyboardNotifications() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardWillShow),
            name: UIResponder.keyboardWillShowNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardWillHide),
            name: UIResponder.keyboardWillHideNotification,
            object: nil
        )
    }
    
    @objc private func keyboardWillShow(_ notification: Notification) {
        guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {
            return
        }
        
        keyboardHeight = keyboardFrame.height
        updateViewsForKeyboard()
    }
    
    @objc private func keyboardWillHide(_ notification: Notification) {
        keyboardHeight = 0
        updateViewsForKeyboard()
    }
    
    private func updateViewsForKeyboard() {
        UIView.animate(withDuration: 0.3) {
            self.markdownView?.snp.updateConstraints { make in
                make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-self.keyboardHeight)
            }
            
            self.editorView.snp.updateConstraints { make in
                make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-self.keyboardHeight)
            }
            
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func dismissKeyboard() {
        editorView.resignFirstResponder()
    }
    
    // MARK: - Gesture Handling
    @objc private func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: view)
        let velocity = gesture.velocity(in: view)
        
        switch gesture.state {
        case .changed:
            if !isPreviewMode && translation.y > 0 {
                dismissKeyboard()
            }
        case .ended:
            if velocity.y > 1000 {
                dismissKeyboard()
            }
        default:
            break
        }
    }
    
    // 添加返回按钮点击事件
    @objc private func backButtonTapped() {
        navigationController?.popViewController(animated: true)
    }
}

// MARK: - UITextViewDelegate
extension MarkdownDetailViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        if isPreviewMode {
            markdownView?.render(textView.text)
        }
    }
}

// MARK: - UIGestureRecognizerDelegate
extension MarkdownDetailViewController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}

// MARK: - MarkdownContentViewDelegate
extension MarkdownDetailViewController: MarkdownContentViewDelegate {
    func markdownContentView(_ view: MarkdownContentView, shouldHandleLink url: URL) -> Bool {
        // 根据链接类型决定是否允许打开
        if url.scheme == "custom" {
            handleCustomLink(url)
            return false
        } else if url.absoluteString.hasPrefix("#") {
            handleInternalLink(url)
            return false
        }
        
        // 对于外部链接，显示确认对话框
        let alert = UIAlertController(
            title: "打开外部链接",
            message: "是否打开链接：\(url.absoluteString)?",
            preferredStyle: .alert
        )
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "打开", style: .default) { [weak self] _ in
            UIApplication.shared.open(url) { success in
                if success {
                    self?.markdownContentView(view, didHandleLink: url)
                } else {
                    let error = NSError(domain: "MarkdownUIKit", code: -1, userInfo: nil)
                    self?.markdownContentView(view, failedToHandleLink: url, error: error)
                }
            }
        })
        
        present(alert, animated: true)
        return false
    }
    
    func markdownContentView(_ view: MarkdownContentView, didHandleLink url: URL) {
        print("成功打开链接：\(url)")
    }
    
    func markdownContentView(_ view: MarkdownContentView, failedToHandleLink url: URL, error: Error) {
        // 显示错误提示
        let alert = UIAlertController(
            title: "链接打开失败",
            message: error.localizedDescription,
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
    
    func markdownContentView(_ view: MarkdownContentView, didTapImage url: URL) {
        // 处理图片点击，可以显示大图等
        print("点击了图片：\(url)")
    }
    
    func markdownContentView(_ view: MarkdownContentView, didTapCustomTag tag: String, attributes: [String: String], content: String) {
        if let className = attributes["class"] {
            let href = attributes["href"] ?? ""
            switch className {
            case "ncTag":
                // 处理引用标签点击
                print("点击了引用标签：\(content) - href: \(href)")
            case "userTag":
                // 处理用户标签点击
                print("点击了引用标签：\(content) - href: \(href)")
            default:
                break
            }
        }
    }
    
    // MARK: - Private Methods
    private func handleCustomLink(_ url: URL) {
        // 处理自定义协议链接
        let alert = UIAlertController(
            title: "自定义链接",
            message: "处理自定义链接：\(url.absoluteString)",
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
    
    private func handleInternalLink(_ url: URL) {
        // 处理内部链接
        let alert = UIAlertController(
            title: "内部链接",
            message: "处理内部链接：\(url.absoluteString)",
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
} 
